<template>
	<view class="setUp">
		<view class="content">
			<view class="setUpTop mt-24">
				<view class="item">
					<view class="label">头像</view>
					<view class="value"  @click="editAvatar">
						<view class="valueText">
							<img :src="userInfo.avatar" alt="" class="pic">
						</view>
						<uni-icons type="right" size="16"></uni-icons>
					</view>
				</view>
				<view class="item">
					<view class="label">昵称</view>
					<view class="value" @click="toUrl('name')">
						<view class="valueText">{{userInfo.nickName}}</view>
						<view class="icon">
							<uni-icons type="right" size="16"></uni-icons>
						</view>
					</view>
				</view>
			</view>
			<view class="setUpTop mt-24" v-if="identity== '0' || identity== 1">
				<view class="item">
					<view class="label">接单地址</view>
					<view class="value" @click="toUrl('address')">
						<uni-icons type="right" size="16"></uni-icons>
					</view>
				</view>
				<view class="text" v-if="userInfo.province && userInfo.province != ''">
					{{userInfo.locationAddress}}{{userInfo.address}}
				</view>
				<view class="item" style="border-top: 1rpx solid #E6E6E6;justify-content: flex-start;">
					<view class="label">服务范围</view>
					<view class="valueText">{{userInfo.orderTakingRange}}KM</view>
				</view>
			</view>
			<view class="setUpTop mt-24" v-if="identity== '0' || identity== 1">
				<view class="item">
					<view class="label">提供服务</view>
					<view class="value" @click="toUrl('service')">
						<uni-icons type="right" size="16"></uni-icons>
					</view>
				</view>
				<view class="text" v-if="userInfo.serviceType && userInfo.serviceType != ''">
					<view class="option" v-for="(item,index) in userInfo.serviceType.split(',')" :key="index">
						{{item == 1 ? '上门喂养' : item == 2 ? '上门遛狗' : '基础清洁'}}
					</view>
				</view>
			</view>
			<view class="setUpTop mt-24" @click="toUrl('introduce')" v-if="identity== '0' || identity== 1">
				<view class="item">
					<view class="label">个人介绍</view>
				</view>
				<view class="text">{{userInfo.petsitterIntroduce}}</view>
			</view>
			<view class="setUpTop mt-24"  v-if="identity== '0' || identity== 1">
				<view class="item" @click="toUrl('album')">
					<view class="label">个人相册</view>
					<view class="value">最多5张</view>
				</view>
				<view class="text">
					<view class="album">
						<view class="media_box" v-for="(fileItem, fileIndex) in JSON.parse(userInfo.petRaisingPic)" :key="fileIndex">
							<view class="mediaWrap">
								<image class="media" :src="fileItem.picUrl" @tap.stop="previewImage(fileItem.picUrl)"></image>
								<!-- <view class="mediaText">{{fileItem.picName.substring(0,fileItem.picName.indexOf('.'))}}</view> -->
								<textarea class="mediaText" type="text" auto-height v-model="fileItem.picName" @blur="editPicName(fileItem)" />
							</view>
							<image class="media_delete" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-100.png" @tap.stop="deleteFile(fileIndex)"></image>
						</view>
						<!-- <view @click.stop="uploadStudioPic" class="uploadBtn">
							<image src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-97.png"></image>
						</view> -->
					</view>
				</view>
			</view>
			<view class="fixedImgBox">
				<image v-if="identity== '0' || identity== 1" @click="uploadStudioPic" class="fixedImg" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-159.png" mode="widthFix"></image>
			</view>
		</view>
		
		
		
		
		<uni-popup ref="popupRef" type="center" border-radius="10px 10px 0 0">
			<view class="popu_box">
				<checkbox-group @change="checkboxChange">
				  <label class="ttui-cell" v-for="(item,index) in detail.checkData" :key="index">
					<view class="ttui-cell__hd">
					  <checkbox :value="item.value" :checked="item.checked" color="#F85959"/>
					</view>
					<view class="ttui-cell__bd">{{item.text}}</view>
				  </label>
				</checkbox-group>
				<view class="popu_btn">
					<view class="xjs-btn-primary-plain btn_box" @tap="closePopup(false)"> 取消</view>
					<view class="xjs-btn-primary" @tap="submitData"> 确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
	import { onShow } from '@dcloudio/uni-app'
	import { useUserStoreToRefs } from '@/store/useUserStore'
	import config from '@/config/index'
	import { ref ,reactive} from 'vue'
	import api from '@/api'
	import { logOut, updateUserInfo }from '@/hooks/useLogin'
	import {useStudioStoreToRefs} from "@/store/useStudioStore";
	import { accredit } from '@/hooks/useAppPermission/index';
	// let {workSpace,studio,identity} = useStudioStoreToRefs()
	const { userInfo, access_token } = useUserStoreToRefs()
	const  popupRef = ref()
	const detailInfo = ref({})
	const identity = ref('')
	const detail = reactive<{
		checkValue:any
		checkData:any
	}>({
		checkValue:[],
		checkData: [{
			text: '上门喂养',
			value: 1,
		}, {
			text: '上门遛狗',
			value: 2
		},{
			text: '基础清洁',
			value: 3,
		}],
	})
	onShow((option) => {
		updateUserInfo()
		getStudioInfo()
	})
	
	const getStudioInfo = async () => {
		const res = await api({
		   method: 'get',
		   url: `/mall/studio/myStudio`
		})
		useStudioStoreToRefs.studioInfo = res.data
		detailInfo.value = res.data.studio
		identity.value = res.data.identity
	}
	
	const checkboxChange = (evt) => {
		// console.log(evt)
		detail.checkValue = evt.detail.value
		const items = detail.checkData, values = evt.detail.value
		for (let i = 0; i < items.length; ++i) {
		  items[i].checked = false;
		  for (let j = 0; j < values.length; ++j) {
			if (items[i].value == values[j]) {
			  items[i].checked = true;
			  break;
			}
		  }
		}
	}
	const closePopup = (type : any) => {
		popupRef.value.close()
	}
	
	const edit = async() => {
		let res:any = await api({
		  method: 'put',
		  url: `/mall/user/updateServiceTypes`,
		  data:{
			  serviceType:detail.checkValue.join(',')
		  }
		})
		if (res.code !== 0) {
			uni.showToast({
				icon: 'none',
				mask: true,
				title: res.msg
			})
			return false
		}else{
			uni.showToast({
				icon: 'none',
				mask: true,
				title: '修改成功'
			})
			closePopup(true)
		}
	}
	const submitData = async() => {
		await edit()
		await updateUserInfo()
	}
	
	const setAvatarApi = async(url:string) => {
		const res : any = await api({
			method: 'put',
			url: `/mall/user/updateAvatar`,
			data:{
				avatar: url
			}
		})
	}
	
	const editAvatar = async () => {
		// #ifdef APP
		const status = await accredit('CAMERA')
		if (status != 1) return
		const status2 = await accredit('READ_EXTERNAL_STORAGE')
		if (status2 != 1) return
		// #endif
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ["camera", "album"], //从相册选择
			success: function (res) {
				uploadImage(res.tempFilePaths[0])
			}
		})
	}
	
	const uploadImage = (filePath) =>{
      uni.uploadFile({
        url: config.api + '/api/mall/user/uploadAvatarPic', 
        filePath: filePath,
        name: 'file', 
		header:{
			'Authorization': access_token.value ? 'Bearer ' + access_token.value :
							'Basic bWFsbC1hcHA6bWFsbC1hcHA=',
			'x-flow-id': new Date().getTime(),
			"x-client-id": ""
		},
        success: async(uploadFileRes) => {
          // console.log(JSON.parse((uploadFileRes.data)).data);
		  await setAvatarApi(JSON.parse((uploadFileRes.data)).data)
		  await updateUserInfo()
        },
        fail: (error) => {
          console.error(error);
        }
      })
	}
	
	const uploadStudioPic = async() => {
		// #ifdef APP
		const status = await accredit('CAMERA')
		if (status != 1) return
		const status2 = await accredit('READ_EXTERNAL_STORAGE')
		if (status2 != 1) return
		// #endif
		if(JSON.parse(userInfo.value.petRaisingPic) && JSON.parse(userInfo.value.petRaisingPic).length >= 5){
			uni.showToast({
			  title: '最多上传5张',
			  icon: 'none',
			})
			return false
		}
		uni.chooseImage({
			count: 20,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ["camera", "album"], //从相册选择
			success: function (res) {
				// let file = res.tempFilePaths.map(v => {
				// 	return{
				// 		picName:v.substring(v.lastIndexOf('/') + 1),
				// 		picUrl:v
				// 	}
				// })
				// for(let i = 0;i<res.tempFilePaths.length;i++){
					// uploadStudioImage(res.tempFilePaths[i])
				// }
				const {tempFilePaths} = res
				Promise.all(
					res.tempFilePaths.map(item => uploadStudioImage(item))
				).then(async  res => {
					let arr = userInfo.value.petRaisingPic ? [...JSON.parse(userInfo.value.petRaisingPic),...res] : [...res]
					// console.error(res,121221,[...JSON.parse(userInfo.value.petRaisingPic),...res])
					if(arr.length > 5){
						uni.showToast({
						  title: '最多上传5张',
						  icon: 'none',
						})
						return false
					}
					await setStudioImageApi(JSON.stringify(arr))
					setTimeout(() => {
						updateUserInfo()
					},500)
				}).catch(msg => {
					console.error(msg);
				});
			}
		})
	}
	
	const uploadStudioImage = (filePath) =>{
		return new Promise((resolve, reject) => {
		  uni.uploadFile({
			url: config.api + '/api/mall/user/uploadPhotoAlbum', 
			filePath: filePath,
			name: 'file', 
			header:{
				'Authorization': access_token.value ? 'Bearer ' + access_token.value :
								'Basic bWFsbC1hcHA6bWFsbC1hcHA=',
				'x-flow-id': new Date().getTime(),
				"x-client-id": ""
			},
			success: async(uploadFileRes) => {
				// console.log(JSON.parse((uploadFileRes.data)).data,
				// filePath.substring(filePath.lastIndexOf('/') + 1))
				let obj = {
					picName:filePath.substring(filePath.lastIndexOf('/') + 1),
					picUrl:JSON.parse((uploadFileRes.data)).data
				}
				resolve(obj)
			},
			fail: (error) => {
			  console.error(error,12122);
			}
		  })
	   })
	}
	
	const setStudioImageApi = async(url:string) => {
		const res : any = await api({
			method: 'put',
			url: `/mall/user/updatePetRaisingPic`,
			data:{
				petRaisingPic: url
			}
		})
	}
	
	const previewImage = (url) => {
		uni.previewImage({
			urls: [url],
			current: 0
		});
	};
	
	const deleteFile = (index) => {
		uni.showModal({
			title: '提示',
			content: '是否删除该文件',
			success: function (res)  {
				if (res.confirm) {
					let arr = JSON.parse(userInfo.value.petRaisingPic)
					arr.splice(index, 1)
					console.log(arr)
					setStudioImageApi(JSON.stringify(arr))
					setTimeout(() => {
						updateUserInfo()
					},500)
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	};
	
	const editPicName = (item) =>{
		if(JSON.parse(userInfo.value.petRaisingPic) && JSON.parse(userInfo.value.petRaisingPic).length > 0){
			let file = JSON.parse(userInfo.value.petRaisingPic)
			file.map(v => {
				if(v.picUrl == item.picUrl){
					v.picName = item.picName
				}
			})
			setStudioImageApi(JSON.stringify(file))
			setTimeout(() => {
				updateUserInfo()
			},500)
		}
	}
	
	const toUrl = (type: string) => {
		if(type == 'name'){
			uni.navigateTo({
				url: `/pages/setting/modifyName/index`
			})
		}else if(type == 'phone'){
			uni.navigateTo({
				url: `/pages/setting/phone/index`
			})
		}else if(type == 'user'){
			uni.navigateTo({
				url: `/pages/setting/userAgreement/index`
			})
		}else if(type == 'privacy'){
			uni.navigateTo({
				url: `/pages/setting/privacyAgreement/index`
			})
		}else if(type == 'address'){
			uni.navigateTo({
				url: `/pages/setting/editAddress/index`
			})
		}else if(type == 'introduce'){
			uni.navigateTo({
				url: `/pages/setting/editIntroduce/index`
			})
		}else if(type == 'service'){
			popupRef.value.open('')
			if(userInfo.value.serviceType && userInfo.value.serviceType != ''){
				detail.checkValue = userInfo.value.serviceType.split(',')
				const items = detail.checkData, values = detail.checkValue
				for (let i = 0; i < items.length; ++i) {
				  items[i].checked = false;
				  for (let j = 0; j < values.length; ++j) {
					if (items[i].value == values[j]) {
					  items[i].checked = true;
					  break;
					}
				  }
				}
			}
		}else if(type == 'album'){
			uni.navigateTo({
				url: `/pages/studio/album/index?studioId=${detailInfo.value.id}&userId=${userInfo.value.id}`
			})
		}
	}
</script>

<style lang="scss" scoped>
.media_box {
	position: relative;
	margin-right: 12rpx;
	margin-bottom: 20rpx;
	&:last-child{
		margin-right: 0;
	}
	.media {
		width: 198rpx;
		height: 198rpx;
	}
	.mediaText{
		width: 198rpx;
		// white-space: nowrap;       
		// overflow: hidden;            
		// text-overflow: ellipsis;
		text-align: center;
		font-size: 24rpx;
		color: #5C5E5E;
		word-wrap: break-word;
		word-break: break-all;
		white-space:pre-wrap;
	}
	.media_delete {
		width: 32rpx;
		height: 32rpx;
		border-radius: 50%;
		position: absolute;
		right: -8rpx;
		top: -8rpx;
	}
}
.uni-px-5 {
	padding-left: 10px;
	padding-right: 10px;
}
.uni-pb-5 {
	padding-bottom: 10px;
}
.popu_box {
		background-color: #fff;
		border-radius: 24rpx;
		padding: 40rpx;
		box-sizing: border-box;
		margin-bottom: 48rpx;
		font-size: 30rpx;
		color: #1B2120;
		width: 600rpx;
	}
	.ttui-cell{
		width: 100%;
		display: flex;
		align-items: center;
		margin-bottom: 40rpx;
		&:last-child{
			margin-right: 8rpx;
		}
	}
	.popu_btn {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 70rpx;
		view {
			width: 46%;
		}
	}
	.fixedImgBox{
		position: fixed;
		bottom: 20%;
		right: 24rpx;
		z-index: 999;
	}
	.fixedImg{
		width: 136rpx;
		height: 180rpx !important;
	}
.setUp{
	width: 100%;
	min-height: 100vh;
	background-color: #F9F6F6;
	padding-bottom: var(--safe-area-bottom);
	// #ifdef APP
	padding-bottom: calc(24rpx + var(--safe-area-bottom));
	// #endif
	box-sizing: border-box;
	.content{
		margin-top: 32rpx;
		padding: 0 32rpx;
	}
	.mt-24{
		margin-bottom: 24rpx;
	}
	.setUpTop{
		padding: 0 32rpx ;
		box-sizing: border-box;
		background-color: #fff;
		border-radius: 24rpx 24rpx 24rpx 24rpx;
		.text{
			position: relative;
			display: flex;
			font-size: 28rpx;
			color: #5C5E5E;
			padding: 32rpx 0 40rpx;
			word-wrap:break-word;
			word-break:break-all;
			.option{
				position: relative;
				margin-right: 40rpx;
				&:last-child{
					margin-right: 0;
					&::after{
						content: none;
					}
				}
				&::after{
					content: '';
					position: absolute;
					right: -20rpx;
					transform: translateY(-50%);
					top: 50%;
					height: 28rpx;
					width: 1rpx;
					background-color: #5C5E5E;
				}
			}
			.album{
				display: flex;
				flex-wrap: wrap;
				align-items: stretch;
				// image{
				// 	width: 198rpx;
				// 	height: 198rpx;
				// }
				// view{
				// 	text-align: center;
				// 	margin-top: 16rpx;
				// 	font-size: 24rpx;
				// 	color: #5C5E5E;
				// }
			}
			.uploadBtn{
				width: 98rpx;
				height: 98rpx;
				border-radius: 50%;
				position: absolute;
				right: -64rpx;
				bottom: -10rpx;
				background-color: #F9F6F6;
				color: #fff;
				font-size: 26rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				image{
					width: 48rpx;
					height: 48rpx;
				}
			}
		}
	}
	.item{
		font-size: 32rpx;
		color: #1A1A1A;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #E6E6E6;
		padding: 40rpx 0;
		box-sizing: border-box;
		&:last-child{
			border: none;
		}
		.label{
			width: 160rpx;
		}
		.value{
			width: calc(100% - 160rpx);
			display: flex;
			align-items: center;
			justify-content: flex-end;
			color: #808080;
			font-size: 28rpx;
			.uniIcon{
				width: 60rpx;
				text-align: right;
			}
		}
		.valueText{
			color: #808080;
			font-size: 28rpx;
			word-break: break-all !important;
			.pic{
				width: 100rpx;
				height: 100rpx;
				background: linear-gradient( 90deg, #FFA6BC 0%, #FFA3A3 100%);
				border-radius: 50%;
			}
		}
	}
	.btn{
		background-color: #fff;
		border-radius: 62rpx 62rpx 62rpx 62rpx;
		text-align: center;
		line-height: 88rpx;
		font-size: 28rpx;
		color: #FF6084;
		letter-spacing: 2rpx;
		font-weight: bold;
	}
}	
</style>